package com.zyx.interceptor;

import com.zyx.context.BaseContextHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>
 *
 * @author Yaxi.Zhang
 * @since 2022/10/7 10:45
 */
@Slf4j
public class ContextHandlerInterceptor implements HandlerInterceptor {

    public static final List<Long> idList = Arrays.asList(1001L, 2001L, 3001L);
    public static final List<String> nameList = Arrays.asList("zhangsan", "list", "wangwu");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            log.info("not exec!!! url={}", request.getRequestURL());
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        int index = ThreadLocalRandom.current().nextInt(3);
        // 这里应该从header中获取token信息，为了简化，随机取值了
        BaseContextHandler.setUserId(idList.get(index));
        BaseContextHandler.setUserName(nameList.get(index));
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
